import { Request } from "express";
import { Service, Response } from "@/middleware/response";
import { DictionaryModel } from "@/models/common/Dictionary";
import { Dictionary, DictionaryItem } from "@/types/common/dictionary";
import { DictionaryItemModel } from "@/models/common/DictionaryItem";
import {
    GetChildrenPageListOptions,
    getChildrenPageList,
    getPageList,
    GetPageListOptions,
    deleteRecord,
    deleteChildRecord,
    createChildRecord,
    createRecord,
    updateRecord,
    catchError,
    getChildrenByParentField,
} from "@/utils/db";
import { PageReq } from "@/types/common/common";

// 字典分页
export const getDicionaries = async (req: Request, res: Response) => {
    const { page, pageSize, ...match } = req.query;
    const { title, key, _id } = match;
    const options: GetPageListOptions<Dictionary> = {
        model: DictionaryModel,
        params: req.query as PageReq,
        $project: { dictItems: 0 },
    };
    if (title || key || _id) options.$match = {};
    if (title && typeof title === "string") options.$match!.title = { $regex: RegExp(title), $options: "i" };
    if (key && typeof key === "string") options.$match!.key = { $regex: RegExp(key), $options: "i" };
    if (_id) options.$match!._id = _id;
    const { total, list } = await getPageList(options);
    res.sendResponse!(200, { total, list });
};

// 通过_id查字典详情
export const getDictionary = async (req: Request, res: Response) => {
    const { _id } = req.params;
    catchError({
        async operation() {
            const result = await getChildrenByParentField({
                model: DictionaryModel,
                $match: { _id },
                localField: "dictItems",
                from: "dictionaryitems",
            });
            res.sendResponse!(200, result);
        },
        res,
        type: "查询",
    });
};

// 通过key查字典详情
export const getDictionaryByKeyService = async (req: Request, res: Response) => {
    const { key } = req.query;
    catchError({
        async operation() {
            const result = await getChildrenByParentField({
                model: DictionaryModel,
                $match: { key },
                localField: "dictItems",
                from: "dictionaryitems",
            });
            res.sendResponse!(200, result);
        },
        res,
        type: "查询",
    });
};

// 创建字典
export const createDictionary: Service = async (req, res) => {
    const { dictionaryItems, ...data } = req.body;
    catchError({
        async operation() {
            await createRecord({
                model: DictionaryModel,
                childFields: [{ key: "dictItems", model: DictionaryItemModel, value: dictionaryItems }],
                data,
            });
            res.sendResponse!(200);
        },
        res,
        type: "创建",
    });
};

// 更新字典
export const updateDictionary: Service = async (req, res) => {
    const { _id, dictItems, ...data } = req.body;
    catchError({
        async operation() {
            await updateRecord({
                model: DictionaryModel,
                _id,
                data,
                childFields: [{ model: DictionaryItemModel, key: "dictItems", value: dictItems }],
            });
            res.sendResponse!(200);
        },
        res,
        type: "更新",
    });
};

// 删除字典
export const deleteDictionary: Service = async (req, res) => {
    const { _id } = req.body;
    catchError({
        async operation() {
            await deleteRecord({
                _id,
                model: DictionaryModel,
                childFields: [{ key: "dictItems", mustBeEmpty: true, label: "字典数据", model: DictionaryItemModel }],
            });
            res.sendResponse!(200, null, "删除成功");
        },
        res,
        type: "删除",
    });
};

// 字典数据分页
export const getDictionaryItems = async (req: Request, res: Response) => {
    const { _id, key, label, value } = req.query;
    const options: GetChildrenPageListOptions<DictionaryItem> = {
        model: DictionaryItemModel,
        params: req.query as PageReq,
        $sort: { srot: -1 },
        parentKey: key ? "key" : "_id",
        parentValue: key ? key : _id,
        parentModel: DictionaryModel,
        localField: "dictItems",
        foreignField: "_id",
    };
    if (label || value) options.$match = {};
    if (typeof label === "string") options.$match!.label = { $regex: RegExp(label), $options: "i" };
    if (typeof value === "string") options.$match!.value = { $regex: RegExp(value), $options: "i" };
    catchError({
        async operation() {
            const result = await getChildrenPageList(options);
            res.sendResponse!(200, result);
        },
        res,
        type: "查询",
    });
};

// 创建字典数据
export const createDictionaryItem: Service = async (req, res) => {
    const { dictionaryId, ...data } = req.body;
    catchError({
        async operation() {
            await createChildRecord({
                parentId: dictionaryId,
                data,
                model: DictionaryItemModel,
                parentModel: DictionaryModel,
                childFields: "dictItems",
            });
            res.sendResponse!(200);
        },
        res,
        type: "创建",
    });
};

export const updateDictionaryItem: Service = async (req, res) => {
    const { _id, ...data } = req.body;
    catchError({
        async operation() {
            const dictionaryItem = await DictionaryItemModel.updateOne({ _id }, data);
            res.sendResponse!(200, dictionaryItem);
        },
        res,
        type: "更新",
    });
};

export const deleteDictionaryItem: Service = async (req, res) => {
    const { _id } = req.body;
    catchError({
        async operation() {
            await deleteChildRecord({ _id, model: DictionaryItemModel, childField: "dictItems", parentModel: DictionaryModel });
            res.sendResponse!(200, null, "删除成功");
        },
        res,
        type: "删除",
    });
};

// 根据字典键、数据值获取数据label
export const getConfigItem = async (key: string, value: string) => {
    const config = await DictionaryModel.aggregate([
        { $match: { key } },
        {
            $lookup: {
                localField: "dictItems",
                foreignField: "_id",
                as: "dictItems",
                from: "dictionaryitems",
                pipeline: [
                    {
                        $match: { value },
                    },
                ],
            },
        },
    ]);
    const configItem = config[0]?.dictItems[0]?.label;
    return configItem;
};

export const getAllDictionaryService: Service = async (req, res) => {
    const data = await DictionaryModel.aggregate([
        {
            $match: { status: true },
        },
        {
            $project: { key: 1, title: 1, dictItems: 1, _id: 0 },
        },
        {
            $sort: { sort: -1 },
        },
        {
            $lookup: {
                localField: "dictItems",
                foreignField: "_id",
                as: "dictItems",
                from: "dictionaryitems",
                pipeline: [
                    {
                        $match: { status: true },
                    },
                    {
                        $project: { label: 1, value: 1, _id: 0, backgroundColor: 1 },
                    },
                    {
                        $sort: { sort: -1 },
                    },
                ],
            },
        },
    ]);
    res.sendResponse!(200, data);
};
